queue介绍
queue是python的标准库,俗称队列.可以直接import引用,在python2.x中,模块名为Queue。python3直接queue即可
在python中,多个线程之间的数据是共享的,多个线程进行数据交换的时候,不能够保证数据的安全性和一致性,所以当多个线程需要进行数据交换的时候,队列就出现了,队列可以完美解决线程间的数据交换,保证线程间数据的安全性和一致性(简单的来说就是多线程需要加锁,很可能会造成死锁,而queue自带锁。所以多线程结合queue会好的很多。案例:https://www.cnblogs.com/nul1/p/9901942.html)
queue模块有三种队列及构造函数:
Python queue模块的FIFO队列先进先出。 class queue.Queue(maxsize)
LIFO类似于堆,即先进后出。 class queue.LifoQueue(maxsize)
还有一种是优先级队列级别越低越先出来。 class queue.PriorityQueue(maxsize)
一:FIFO先进先出
FIFO即First in First Out,先进先出。Queue提供了一个基本的FIFO容器,使用方法很简单,maxsize是个整数,指明了队列中能存放的数据个数的上限。一旦达到上限,插入会导致阻塞,直到队列中的数据被消费掉。如果maxsize小于或者等于0,队列大小没有限制。
1 import Queue
2 q = Queue.Queue()
3 for i in range(5):
4 q.put(i)
5 while not q.empty():
6 print q.get()
输出:
0
1
2
3
4
二:LIFO先进先出
LIFO即Last in First Out,后进先出。与栈的类似,使用也很简单,maxsize用法同上
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import Queue
2
3 q = Queue.LifoQueue()
4
5 for i in range(5):
6 q.put(i)
7
8 while not q.empty():
9 print q.get()
View Code
输出:
4
3
2
1
0
三:优先级队列
class Queue.PriorityQueue(maxsize=0)
构造一个优先队列。maxsize用法同上。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import Queue
2 import threading
3
4 class Job(object):
5 def __init__(self, priority, description):
6 self.priority = priority
7 self.description = description
8 print 'Job:',description
9 return
10 def __cmp__(self, other):
11 return cmp(self.priority, other.priority)
12
13 q = Queue.PriorityQueue()
14
15 q.put(Job(3, 'level 3 job'))
16 q.put(Job(10, 'level 10 job'))
17 q.put(Job(1, 'level 1 job'))
18
19 def process_job(q):
20 while True:
21 next_job = q.get()
22 print 'for:', next_job.description
23 q.task_done()
24
25 workers = [threading.Thread(target=process_job, args=(q,)),
26 threading.Thread(target=process_job, args=(q,))
27 ]
28
29 for w in workers:
30 w.setDaemon(True)
31 w.start()
32
33 q.join()
View Code
Job: level 3 job
Job: level 10 job
Job: level 1 job
for: level 1 job
for: level 3 job
for: level 10 job
queue模块中的常用方法:
queue.qsize() 返回队列的大小
queue.empty() 如果队列为空,返回True,反之False
queue.full() 如果队列满了,返回True,反之False
queue.full 与 maxsize 大小对应
queue.get([block[, timeout]])获取队列,timeout等待时间
queue.get_nowait() 相当queue.get(False)
queue.put(item) 写入队列,timeout等待时间
queue.put_nowait(item) 相当queue.put(item, False)
queue.task_done() 在完成一项工作之后,queue.task_done()函数向任务已经完成的队列发送一个信号
queue.join() 实际上意味着等到队列为空,再执行别的操作
|